using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using CustomLitJson;
using System.Linq;
using System.IO;
using System.Threading.Tasks;

public static class ProjectBuildPipline 
{

    static List<Type> _schemaTypeList;
    public static List<Type> SchemaTypeList
    {
        get
        {
            if(_schemaTypeList == null)
            {
                var list = ReflectionUtil.GetSubClassesInAllAssemblies<BuildSchema>();
                _schemaTypeList = list;
            }
            return _schemaTypeList;
        }
    }

    public static Type GetParamTypeOfSchema(Type schemaType)
    {
        var paramType = schemaType.GetNestedType("Param");
        return paramType;
    }

    //public static List<ParamAttribute> GetSchemaParamList(string schemaName)
    //{
    //    var ret = new List<ParamAttribute>();
    //    var type = FindSchemaTypeByName(schemaName);
    //    var attributeList = type.GetCustomAttributes(typeof(ParamAttribute), true);
    //    if (attributeList == null || attributeList.Length == 0)
    //    {
    //        return ret;
    //    }
    //    foreach(var one in attributeList)
    //    {
    //        ret.Add(one as ParamAttribute);
    //    }
      
    //    return ret;
    //}

    public static Type FindSchemaTypeByName(string name)
    {
        foreach(var schema in SchemaTypeList)
        {
            if(schema.Name == name)
            {
                return schema;
            }
        }
        throw new Exception($"[ProjectBuildPipline] Schema '{name}' not found");
    }

    //static Dictionary<string, string> NormalizeParamDic(string schemaName, Dictionary<string, string> paramDic)
    //{
    //    var newDic = new Dictionary<string, string>();
    //    var attrList = GetSchemaParamList(schemaName);
    //    foreach(var attr in attrList)
    //    {
    //        var name = attr.key;
    //        var defaultValue = attr.defaultValue;
    //        var value = DictionaryUtil.TryGet(paramDic, name, defaultValue);
    //        newDic[name] = value;
    //    }
    //    return newDic;
    //}

    public static async Task Build(string name, object param, string env, string switchToPlatformIfNeed = null)
    {
        if(string.IsNullOrEmpty(env))
        {
            throw new Exception("[ProjectBuildPipline] need param 'env'");
        }

        if(!string.IsNullOrEmpty(switchToPlatformIfNeed))
        {
            Debug.Log("[ProjectBuildPipline] switch to platform: " + switchToPlatformIfNeed);
            if (switchToPlatformIfNeed.ToLower() == "android")
            {
                EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
            }
            else
            {
                throw new Exception("[ProjectBuildPipline] not support switch to platform: " + switchToPlatformIfNeed);
            }
            Debug.Log("[ProjectBuildPipline] switch platform complete");
        }

        var envInfo = BuildManifestManager.GetEnvInfo(env);


        var type = FindSchemaTypeByName(name);
        var schema = Activator.CreateInstance(type) as BuildSchema;
        schema.envName = env;
        schema.envInfo = envInfo;

        try
        {
            Debug.Log($"[ProjectBuildPipline] schame '{name}' started");
            await schema.Build(param);
            Debug.Log($"[ProjectBuildPipline] schame '{name}' build compleate");
        }
        finally
        {
            EditorUtility.ClearProgressBar();
        }

    }

    public static void WriteParamTemplate(Type schemaType, object param, string tempalteName)
    {
        var path = $"ProjectSettings/com.pzy.projectBuildPipline/{schemaType.Name}/{tempalteName}.json";
        var json = JsonMapper.Instance.ToJson(param);

        var dirPath = Path.GetDirectoryName(path);
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }
        File.WriteAllText(path, json);
    }

    public static object ReadParamTempalte(Type schemaType, string tempalteName)
    {
        var path = $"ProjectSettings/com.pzy.projectBuildPipline/{schemaType.Name}/{tempalteName}.json";
        var json = File.ReadAllText(path);
        var paramType = ProjectBuildPipline.GetParamTypeOfSchema(schemaType);
        var param = JsonMapper.Instance.ToObject(paramType, json);
        return param;
    }

    //static void WriteBuildInfoFile(Dictionary<string, string> dic)
    //{
    //    var json = JsonMapper.Instance.ToJson(dic);
    //    json = JsonUtil.Buitify(json);
    //    var path = "Assets/Resources/build-info.json";
    //    var dir = Path.GetDirectoryName(path);
    //    if(!Directory.Exists(dir))
    //    {
    //        Directory.CreateDirectory(dir);
    //    }
    //    File.WriteAllText(path, json);
    //    Debug.Log("[ProjectBuildPipline] build-info.json: " + json);
    //    AssetDatabase.Refresh();

    //}




}
